<script>
import {
  defineComponent,
  reactive,
  toRefs, onMounted, watch
} from 'vue'

export default defineComponent({
  name: 'ConfigCombo',
  props: {
    width: {
      type: [Number, String],
      default: 450
    },
    value: {
      type: [String, Number],
      default: 'value'
    },
    options: {
      type: Array,
      default: () => {
        return [
          { label: 'label', value: 'value' }
        ]
      }
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      currentValue: -1,
      comboListVisible: false
    })

    watch(() => props.value, (e) => {
      state.currentValue = e
    })

    watch(() => state.currentValue, (e) => {
      emit('update:value', e)
    })

    onMounted(() => {
      state.currentValue = props.value
    })

    const getComboLabel = (e) => {
      let result = ''
      props.options.forEach(item => {
        if(item['value'] === e) {
          result = item['label']
        }
      })

      return result
    }

    const handleComboClick = () => {
      state.comboListVisible = !state.comboListVisible
    }

    const handleComboChange = (e) => {
      state.currentValue = props.options[e]['value']
      handleComboClick()
    }

    return {
      ...toRefs(state),
      getComboLabel,
      handleComboClick,
      handleComboChange
    }
  }
})
</script>

<template>
  <div class="component-config-combo-container" :style="{ width: `${typeof width === 'string' ? width : width + 'px'}` }">
    <div class="combo-show" @click="handleComboClick">{{ getComboLabel(currentValue) }}</div>
    <div class="combo-list" :style="{ width: `${typeof width === 'string' ? width : width + 'px'}` }" v-if="comboListVisible">
      <div class="combo-list-item" v-for="(item, index) in options" :key="options" :title="item['label']"
           :class="index === currentValue ? 'active' : ''" @click="handleComboChange(index)">
        {{ item['label'] }}
      </div>
    </div>
  </div>
</template>

<style lang="scss">
.component-config-combo-container {
  position: relative;
  height: 28px;

  .combo-show {
    border: 1px solid #A0A0A0;
    height: 100%;
    padding-left: 12px;
    background-color: #fff;
    display: flex;
    align-items: center;
    user-select: none;
    cursor: pointer;
    overflow:hidden;
    text-overflow:ellipsis;
    white-space:nowrap;
  }

  .combo-list {
    border: 1px solid #A0A0A0;
    user-select: none;
    cursor: pointer;
    background-color: #fff;
    position: absolute;

    .combo-list-item {
      height: 28px;
      line-height: 28px;
      overflow:hidden;
      text-overflow:ellipsis;
      white-space:nowrap;
      padding-left: 12px;

      &.active {
        background-color: #74bcff;
      }

      &:hover {
        background-color: #74bcff60;
      }
    }
  }
}
</style>
